// API配置
const API_BASE_URL = 'http://localhost:19000';

// API辅助函数
function apiCall(endpoint, options = {}) {
    const url = `${API_BASE_URL}${endpoint}`;
    const defaultOptions = {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
        }
    };
    
    return fetch(url, { ...defaultOptions, ...options })
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            updateConnectionStatus(true);
            return response.json();
        })
        .catch(error => {
            console.error(`API调用失败 ${endpoint}:`, error);
            updateConnectionStatus(false);
            throw error;
        });
}

// 更新连接状态
function updateConnectionStatus(isConnected) {
    const statusElement = document.getElementById('connection-status');
    if (isConnected) {
        statusElement.innerHTML = '<i class="bi bi-circle-fill text-success"></i> 已连接';
    } else {
        statusElement.innerHTML = '<i class="bi bi-circle-fill text-danger"></i> 连接失败';
    }
}

// 模拟数据
let progressData = [];
let qualityData = [];
let managementData = [];

// 初始化数据
function initializeData() {
    // 进度数据
    progressData = [
        {
            orderId: "WO-2024-001",
            factory: "factory1",
            workshop: "workshop1",
            line: "line1",
            inputQty: 1000,
            completedQty: 850,
            yield: 98.5,
            defectQty: 13,
            orderCompletedQty: 850,
            scrapQty: 5,
            reworkQty: 8,
            status: "running"
        },
        {
            orderId: "WO-2024-002",
            factory: "factory1",
            workshop: "workshop2",
            line: "line2",
            inputQty: 800,
            completedQty: 800,
            yield: 99.2,
            defectQty: 6,
            orderCompletedQty: 800,
            scrapQty: 2,
            reworkQty: 4,
            status: "completed"
        },
        {
            orderId: "WO-2024-003",
            factory: "factory2",
            workshop: "workshop1",
            line: "line1",
            inputQty: 1200,
            completedQty: 600,
            yield: 97.8,
            defectQty: 26,
            orderCompletedQty: 600,
            scrapQty: 8,
            reworkQty: 18,
            status: "running"
        },
        {
            orderId: "WO-2024-004",
            factory: "factory2",
            workshop: "workshop3",
            line: "line3",
            inputQty: 500,
            completedQty: 0,
            yield: 0,
            defectQty: 0,
            orderCompletedQty: 0,
            scrapQty: 0,
            reworkQty: 0,
            status: "paused"
        },
        {
            orderId: "WO-2024-005",
            factory: "factory3",
            workshop: "workshop1",
            line: "line2",
            inputQty: 900,
            completedQty: 720,
            yield: 98.9,
            defectQty: 8,
            orderCompletedQty: 720,
            scrapQty: 3,
            reworkQty: 5,
            status: "running"
        }
    ];

    // 品质数据
    qualityData = [
        {
            orderId: "WO-2024-001",
            strippingYield: 99.2,
            interferenceYield: 98.8,
            endInspectionYield: 99.5,
            insertionLossYield: 98.9,
            polarityYield: 99.1,
            overallYield: 98.5
        },
        {
            orderId: "WO-2024-002",
            strippingYield: 99.8,
            interferenceYield: 99.5,
            endInspectionYield: 99.9,
            insertionLossYield: 99.2,
            polarityYield: 99.6,
            overallYield: 99.2
        },
        {
            orderId: "WO-2024-003",
            strippingYield: 98.5,
            interferenceYield: 97.9,
            endInspectionYield: 98.2,
            insertionLossYield: 97.5,
            polarityYield: 98.1,
            overallYield: 97.8
        },
        {
            orderId: "WO-2024-004",
            strippingYield: 0,
            interferenceYield: 0,
            endInspectionYield: 0,
            insertionLossYield: 0,
            polarityYield: 0,
            overallYield: 0
        },
        {
            orderId: "WO-2024-005",
            strippingYield: 99.3,
            interferenceYield: 99.1,
            endInspectionYield: 99.4,
            insertionLossYield: 98.8,
            polarityYield: 99.2,
            overallYield: 98.9
        }
    ];

    // 人机料法环数据
    managementData = [
        {
            process: "剥纤",
            personnel: "张三",
            equipment: "剥纤机-A01",
            drawing: "已上传",
            sop: "已上传",
            temperature: "22°C",
            humidity: "45%",
            status: "正常"
        },
        {
            process: "干涉",
            personnel: "李四",
            equipment: "干涉仪-B02",
            drawing: "已上传",
            sop: "已上传",
            temperature: "23°C",
            humidity: "46%",
            status: "正常"
        },
        {
            process: "端检",
            personnel: "王五",
            equipment: "端检仪-C03",
            drawing: "已上传",
            sop: "已上传",
            temperature: "21°C",
            humidity: "44%",
            status: "正常"
        },
        {
            process: "插回损",
            personnel: "赵六",
            equipment: "插回损测试仪-D04",
            drawing: "已上传",
            sop: "已上传",
            temperature: "22°C",
            humidity: "45%",
            status: "正常"
        },
        {
            process: "极性",
            personnel: "钱七",
            equipment: "极性测试仪-E05",
            drawing: "已上传",
            sop: "已上传",
            temperature: "22°C",
            humidity: "45%",
            status: "正常"
        }
    ];
}

// 更新当前时间
function updateCurrentTime() {
    const now = new Date();
    const timeString = now.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
    document.getElementById('current-time').textContent = timeString;
}

// 渲染进度表格
function renderProgressTable(data) {
    const tbody = document.getElementById('progress-tbody');
    tbody.innerHTML = '';

    data.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td><strong>${item.orderId}</strong></td>
            <td>${item.inputQty.toLocaleString()}/${item.completedQty.toLocaleString()}</td>
            <td>
                <div class="d-flex align-items-center">
                    <span class="me-1">${item.yield}%</span>
                    <div class="progress flex-grow-1" style="height: 4px;">
                        <div class="progress-bar bg-success" style="width: ${item.yield}%"></div>
                    </div>
                </div>
            </td>
            <td>${item.defectQty}/${item.scrapQty}</td>
            <td>
                <span class="status-badge status-${item.status}">
                    ${getStatusText(item.status)}
                </span>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 渲染品质表格
function renderQualityTable(data) {
    const tbody = document.getElementById('quality-tbody');
    tbody.innerHTML = '';

    data.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td><strong>${item.orderId}</strong></td>
            <td>
                <span class="quality-indicator ${getQualityClass(item.strippingYield)}">
                    ${item.strippingYield}%
                </span>
            </td>
            <td>
                <span class="quality-indicator ${getQualityClass(item.interferenceYield)}">
                    ${item.interferenceYield}%
                </span>
            </td>
            <td>
                <span class="quality-indicator ${getQualityClass(item.endInspectionYield)}">
                    ${item.endInspectionYield}%
                </span>
            </td>
            <td>
                <span class="quality-indicator ${getQualityClass(item.insertionLossYield)}">
                    ${item.insertionLossYield}%
                </span>
            </td>
            <td>
                <span class="quality-indicator ${getQualityClass(item.polarityYield)}">
                    ${item.polarityYield}%
                </span>
            </td>
            <td>
                <span class="quality-indicator ${getQualityClass(item.overallYield)}">
                    <strong>${item.overallYield}%</strong>
                </span>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 渲染人机料法环表格
function renderManagementTable(data) {
    const tbody = document.getElementById('management-tbody');
    tbody.innerHTML = '';

    data.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td><strong>${item.process}</strong></td>
            <td>${item.personnel}</td>
            <td>${item.equipment}</td>
            <td>
                <span class="badge bg-success">${item.drawing}</span>
            </td>
            <td>${item.temperature}/${item.humidity}</td>
            <td>
                <span class="status-badge status-running">${item.status}</span>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 更新关键指标（保留函数以备后用）
function updateMetrics() {
    // 由于去掉了总体统计显示，此函数暂时保留以备后用
    const totalOrders = progressData.length;
    const runningOrders = progressData.filter(item => item.status === 'running').length;
    const avgYield = progressData.length > 0 ? 
        (progressData.reduce((sum, item) => sum + item.yield, 0) / progressData.length).toFixed(1) : 0;
    const completionRate = progressData.length > 0 ?
        (progressData.reduce((sum, item) => sum + (item.completedQty / item.inputQty * 100), 0) / progressData.length).toFixed(1) : 0;

    // 可以在控制台输出统计信息用于调试
    console.log('数据统计:', {
        totalOrders,
        runningOrders,
        avgYield: avgYield + '%',
        completionRate: completionRate + '%'
    });
}

// 筛选数据
function filterData() {
    const factory = document.getElementById('factory-select').value;
    const workshop = document.getElementById('workshop-select').value;
    const line = document.getElementById('line-select').value;
    const status = document.getElementById('status-select').value;

    let filteredProgressData = progressData.filter(item => {
        return (!factory || item.factory === factory) &&
               (!workshop || item.workshop === workshop) &&
               (!line || item.line === line) &&
               (!status || item.status === status);
    });

    // 根据筛选的进度数据筛选品质数据
    let filteredQualityData = qualityData.filter(item => {
        return filteredProgressData.some(progress => progress.orderId === item.orderId);
    });

    renderProgressTable(filteredProgressData);
    renderQualityTable(filteredQualityData);
    renderManagementTable(managementData);
    updateMetrics();
}

// 清除筛选
function clearFilters() {
    document.getElementById('factory-select').value = '';
    document.getElementById('workshop-select').value = '';
    document.getElementById('line-select').value = '';
    document.getElementById('status-select').value = '';
    
    // 重新加载所有数据
    renderProgressTable(progressData);
    renderQualityTable(qualityData);
    renderManagementTable(managementData);
    updateMetrics();
    
    showToast('筛选条件已清除');
}

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        'running': '生产中',
        'completed': '已完成',
        'paused': '暂停'
    };
    return statusMap[status] || status;
}

// 获取品质等级样式
function getQualityClass(yield) {
    if (yield >= 99) return 'quality-excellent';
    if (yield >= 98) return 'quality-good';
    if (yield >= 95) return 'quality-warning';
    return 'quality-poor';
}

// 刷新数据
function refreshData() {
    console.log('刷新数据...');
    
    // 调用后端API
    apiCall('/api/refresh')
        .then(data => {
            if (data.success) {
                // 重新加载所有数据
                loadAllData();
                showToast('数据已刷新');
            } else {
                showToast('刷新失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('刷新数据失败:', error);
            showToast('刷新失败，请检查网络连接');
        });
}

// 加载所有数据
function loadAllData() {
    // 加载进度数据
    apiCall('/api/progress')
        .then(data => {
            if (data.success) {
                progressData = data.data;
                renderProgressTable(progressData);
                updateMetrics();
                console.log('进度数据加载成功');
            }
        })
        .catch(error => {
            console.error('加载进度数据失败:', error);
            showToast('加载进度数据失败，使用本地数据');
            renderProgressTable(progressData);
        });
    
    // 加载品质数据
    apiCall('/api/quality')
        .then(data => {
            if (data.success) {
                qualityData = data.data;
                renderQualityTable(qualityData);
                console.log('品质数据加载成功');
            }
        })
        .catch(error => {
            console.error('加载品质数据失败:', error);
            renderQualityTable(qualityData);
        });
    
    // 加载人机料法环数据
    apiCall('/api/management')
        .then(data => {
            if (data.success) {
                managementData = data.data;
                renderManagementTable(managementData);
                console.log('管理数据加载成功');
            }
        })
        .catch(error => {
            console.error('加载管理数据失败:', error);
            renderManagementTable(managementData);
        });
    
    // 加载仪表板数据
    apiCall('/api/dashboard')
        .then(data => {
            if (data.success) {
                updateDashboardMetrics(data.data);
                console.log('仪表板数据加载成功');
            }
        })
        .catch(error => {
            console.error('加载仪表板数据失败:', error);
            updateMetrics();
        });
}

// 更新仪表板指标（保留函数以备后用）
function updateDashboardMetrics(data) {
    // 由于去掉了总体统计显示，此函数暂时保留以备后用
    console.log('仪表板数据:', data);
}

// 显示提示信息
function showToast(message) {
    // 创建toast元素
    const toast = document.createElement('div');
    toast.className = 'position-fixed top-0 end-0 p-3';
    toast.style.zIndex = '1050';
    toast.innerHTML = `
        <div class="toast show" role="alert">
            <div class="toast-header">
                <strong class="me-auto">系统提示</strong>
                <button type="button" class="btn-close" onclick="this.closest('.toast').remove()"></button>
            </div>
            <div class="toast-body">
                ${message}
            </div>
        </div>
    `;
    
    document.body.appendChild(toast);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (toast.parentNode) {
            toast.remove();
        }
    }, 3000);
}

// 测试API连接
function testConnection() {
    console.log('测试API连接...', API_BASE_URL);
    
    // 首先尝试一个简单的fetch请求
    fetch(`${API_BASE_URL}/api/dashboard`)
        .then(response => {
            console.log('原始响应状态:', response.status, response.statusText);
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('API连接测试成功:', data);
            updateConnectionStatus(true);
            showToast('服务器连接成功！');
            return true;
        })
        .catch(error => {
            console.error('API连接测试失败:', error);
            console.error('错误详情:', {
                message: error.message,
                stack: error.stack,
                url: `${API_BASE_URL}/api/dashboard`
            });
            updateConnectionStatus(false);
            showToast('无法连接到服务器，使用离线数据');
            return false;
        });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化本地数据（作为备用）
    initializeData();
    
    updateCurrentTime();
    
    // 测试连接
    setTimeout(() => {
        testConnection();
        // 延迟加载数据，确保连接状态已更新
        setTimeout(loadAllData, 500);
    }, 100);
    
    // 每秒更新时间
    setInterval(updateCurrentTime, 1000);
    
    // 每30秒自动刷新数据
    setInterval(refreshData, 30000);
});
